from __future__ import print_function
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
import math

from config import args


def mse_loss(pred: torch.Tensor, target: torch.Tensor, thr=args.mse_thr):

    return torch.relu(F.mse_loss(pred, target, reduction='none').sum(1) - thr).mean()


class FocalLoss(nn.Module):

    def __init__(self, gamma=args.f_gamma):
        super(FocalLoss, self).__init__()
        self.gamma = gamma
        self.ce = torch.nn.CrossEntropyLoss()

    def forward(self, input, target):
        logp = self.ce(input, target)
        p = torch.exp(-logp)
        p_true = 1
        if args.do_label_smoothing:
            p_true = 1 - args.label_smoothing / args.class_num * (args.class_num - 1)
        loss = (p_true - p) ** self.gamma * logp
        return loss.mean()


class ArcMarginProduct(nn.Module):
    r"""Implement of large margin arc distance: :
        Args:
            in_features: size of each input sample
            out_features: size of each output sample
            s: norm of input feature
            m: margin

            cos(theta + m)
        """
    def __init__(self, in_features, out_features, s=args.arc_s, m=args.arc_m, easy_margin=False):
        super(ArcMarginProduct, self).__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.s = s
        self.m = m
        self.weight = Parameter(torch.FloatTensor(out_features, in_features))
        nn.init.xavier_uniform_(self.weight)

        self.easy_margin = easy_margin
        self.cos_m = math.cos(m)
        self.sin_m = math.sin(m)
        self.th = math.cos(math.pi - m)
        self.mm = math.sin(math.pi - m) * m

    def forward(self, input, label=None):
        # if label is None:
        #     return F.linear(input, self.weight)
        # --------------------------- cos(theta) & phi(theta) ---------------------------
        cosine = F.linear(F.normalize(input), F.normalize(self.weight))
        if label is None:
            return cosine
        sine = torch.sqrt((1.0 - torch.pow(cosine, 2)).clamp(0, 1))
        phi = cosine * self.cos_m - sine * self.sin_m
        if self.easy_margin:
            phi = torch.where(cosine > 0, phi, cosine)
        else:
            phi = torch.where(cosine > self.th, phi, cosine - self.mm)
        # --------------------------- convert label to one-hot ---------------------------
        # one_hot = torch.zeros(cosine.size(), requires_grad=True, device='cuda')
        one_hot = torch.zeros(cosine.size(), device='cuda')
        if not args.use_focal:
            label = label.argmax(1)
        one_hot.scatter_(1, label.view(-1, 1).long(), 1)
        # -------------torch.where(out_i = {x_i if condition_i else y_i) -------------
        output = (one_hot * phi) + ((1.0 - one_hot) * cosine)  # you can use torch.where if your torch.__version__ is 0.4
        output *= self.s

        # print(output)

        return output


if __name__ == '__main__':
    from dataset import BaldClassificationDataset
    from torch.utils.data import DataLoader
    from torch import Tensor as T

    from model import get_models

    dataset_train = BaldClassificationDataset(split='train')
    dataloader_train = DataLoader(dataset_train, batch_size=4, shuffle=args.shuffle)

    if args.multi_model:
        net1, net2 = get_models()
    else:
        net1 = get_models()
    for i, sample in enumerate(dataloader_train):
        imgs, labels, _ = sample
        imgs = imgs.cuda()
        labels = labels.cuda()

        pred = net1(imgs, labels)
        print(pred)

    # a = T([[0.55, 0.45]])
    # b = T([[0.9, 0.1]])
    # print(mse_loss(a, b))
